package basketball_behaviour

import (
	"github.com/shopspring/decimal"
	"longmen/server/internal/services/nami/services/sports/basketball/bbcache"
	"longmen/server/internal/services/nami/utils"
	"longmen/server/pkg/db/mysql/models/models_sports"
	"strconv"
	"strings"
)

type (
	OddsList            map[string][][]interface{}
	OddsLiveApiResponse struct {
		Code    int      `json:"code"`
		Results OddsList `json:"results"`
	}
)

func (odds OddsList) GetByOdds() ([]models_sports.BasketballOdds, []bbcache.Odds) {
	mysqlRecords := make([]models_sports.BasketballOdds, 0)
	oddsRedis := make([]bbcache.Odds, 0)
	for companyId := range odds {
		companyOdds := odds[companyId]
		for _, odd := range companyOdds {
			matchId, ok := odd[0].(float64)
			if !ok {
				// 未知赛事数据
				continue
			}
			exponentialType, ok := odd[1].(string)
			if !ok {
				// 未知指数类型数据
				continue
			}
			oddsItem, ok := odd[2].([]interface{})
			if !ok || len(oddsItem) < 4 {
				// 未知指数数据
				continue
			}
			exponentialScore, ok := odd[3].(string)
			if !ok {
				// 未知指数数据
				continue
			}
			cid, _ := strconv.Atoi(companyId)
			oddsText := strings.Split(oddsItem[2].(string), ",")
			odds2 := decimal.NewFromFloat(utils.StringToFloat(oddsText[1]))
			if exponentialType == "asia" {
				// 正变负，负变正，0不变
				if odds2.LessThan(decimal.Zero) {
					odds2 = odds2.Abs()
				} else if odds2.GreaterThan(decimal.Zero) {
					odds2 = odds2.Neg()
				}
			}

			mysqlRecords = append(mysqlRecords, models_sports.BasketballOdds{
				CompanyId:        cid,
				ExponentialType:  exponentialType,
				ExponentialScore: exponentialScore,
				MatchId:          int(matchId),
				MatchStatus:      utils.GetInt(oddsItem[3]),
				OddsStatus:       utils.StringToInt(oddsText[3]),
				Odds1:            decimal.NewFromFloat(utils.StringToFloat(oddsText[0])),
				Odds2:            odds2,
				Odds3:            decimal.NewFromFloat(utils.StringToFloat(oddsText[2])),
				ChangeTime:       utils.GetInt64(oddsItem[0]),
				CompetitionTime:  oddsItem[1].(string),
			})
			oddsRedis = append(oddsRedis, bbcache.Odds{
				CompanyId:        cid,
				ExponentialType:  exponentialType,
				ExponentialScore: exponentialScore,
				MatchId:          int(matchId),
				MatchStatus:      utils.GetInt(oddsItem[3]),
				OddsStatus:       utils.StringToInt(oddsText[3]),
				Odds1:            decimal.NewFromFloat(utils.StringToFloat(oddsText[0])),
				Odds2:            odds2,
				Odds3:            decimal.NewFromFloat(utils.StringToFloat(oddsText[2])),
				ChangeTime:       utils.GetInt64(oddsItem[0]),
				CompetitionTime:  oddsItem[1].(string),
			})
		}

	}
	return mysqlRecords, oddsRedis
}
